<?php
include_once(Settings::getValue("root")."system/interfaces/iapiprovider.php");

/**
 * Serializes a datatype to xml.
 *
 * @author Stefan Wienstroeer
 */
class XmlSerializer implements IApiProvider{
    
    /**
     *
     * @param mixed $object
     * @param DataType $datatype 
     */
    public function serialize($object,DataType $datatype) {
        header("Content-Type:text/xml");
        echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        echo "<apiresponse datatype=\"".$datatype->getDataName()."\">";
        echo $this->getSerializeCode($object,$datatype->getDataName());
        echo "</apiresponse>";
    }
    
    /**
     *
     * @param int $id
     * @param string $message 
     */
    public function raiseError($id,$message){
        header("Content-Type:text/xml");
        echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        echo "<apiresponse datatype=\"error\">";
        echo "<id>".htmlentities($id)."</id>";
        echo "<message>".htmlentities($message)."</message>";
        echo "</apiresponse>";
        
    }
    
    /**
     *
     * @param mixed $object
     * @return string 
     */
    private function getSerializeCode($object){
        $res = "";
        
        if(is_array($object) || is_object($object)){
            foreach($object as $key=>$value){
                if(is_numeric($key)){
                    $res .= "<item id=\"".$key."\">";
                    $res .= $this->getSerializeCode($value);
                    $res .= "</item>";
                }
                else{
                    $res .= "<".htmlspecialchars($key).">";
                    $res .= $this->getSerializeCode($value);
                    $res .= "</".htmlspecialchars($key).">";
                }
            }
        }
        else{
            $res .= utf8_encode(htmlspecialchars($object));
        }
        
        
        return $res;
    }
    
    /**
     *
     * @param string $url 
     */
    public function importFromUrl($url){
        $response = simplexml_load_file($url);
        if($response){
            $meta = $response->attributes();
            $dataType = DataType::GetByName($meta['datatype']);
            foreach($response->item as $item){
                $params = array();
                foreach($item as $key=>$value){
                    $params[$key] = $value."";
                }
                if($dataType->validate($params)){
                    foreach($params as $key=>$value){
                        $params[$key] = "'".DataBase::Current()->EscapeString($params[$key])."'";
                    }
                    DataBase::Current()->Execute($dataType->getInsertStatement($params));
                    echo "1";
                }
                else{
                    echo "0";
                }
            }
        }
    }
    
}

?>
